package com.runen.wnhz.runen.ui.adapter.puadapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.bean.CourseDetailCommentBean;
import com.runen.wnhz.runen.bean.PingLunBean;
import com.runen.wnhz.runen.bean.WantLearnBean;
import com.runen.wnhz.runen.common.utils.ACacheUtlis;
import com.runen.wnhz.runen.common.utils.NetUtils;
import com.runen.wnhz.runen.common.utils.OkHttpUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.data.entity.UserBean;
import com.runen.wnhz.runen.ui.activity.login.LoginForPersonalActivity;
import com.runen.wnhz.runen.ui.fragment.minem.MessageFragment;
import com.runen.wnhz.runen.widget.coustomview.CircleImageView;

import org.simple.eventbus.EventBus;

import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class CourseCommentRecyclerAdapter extends RecyclerView.Adapter<com.runen.wnhz.runen.ui.adapter.puadapter.CourseCommentRecyclerAdapter.ViewHolder> {

    private Context context;

    private List<CourseDetailCommentBean.DataBean.ListBean> listBeans;

    private String lid;

    private boolean hasGivenThumbsUp = false;

    private String token;

    private  WantLearnBean wantLearnBean = null;

    private int position;

    private MessageFragment messageFragment;

    public void setMessageFragment(MessageFragment messageFragment) {
        this.messageFragment = messageFragment;
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    ToastUtil.showToast("点赞失败");
                    break;
                case 1:
                    ViewHolder holder1 = (ViewHolder) msg.obj;
                    if (wantLearnBean != null) {
                        if ("1".equals(wantLearnBean.getRe())) {
                            ToastUtil.showToast(wantLearnBean.getInfo());
                            holder1.image_giveTheThumbsUp.setImageResource(R.mipmap.have_want_learn_xin);
                            hasGivenThumbsUp = true;
                            PingLunBean pingLunBean = new PingLunBean();
                            EventBus.getDefault().post(pingLunBean);
                        } else if ("0".equals(wantLearnBean.getRe())) {
                            ToastUtil.showToast(wantLearnBean.getInfo());
                        } else if ("-1".equals(wantLearnBean.getRe())){
                            ToastUtil.showToast(wantLearnBean.getInfo());
                            context.startActivity(new Intent(context, LoginForPersonalActivity.class));
                        }
                    }
                    break;
                case 2:
                    ViewHolder holder = (ViewHolder) msg.obj;
                    if (wantLearnBean != null) {
                        if ("1".equals(wantLearnBean.getRe())) {
                            ToastUtil.showToast(wantLearnBean.getInfo());
                            holder.image_giveTheThumbsUp.setImageResource(R.mipmap.icon_want);
                            hasGivenThumbsUp = false;
                            PingLunBean pingLunBean = new PingLunBean();
                            EventBus.getDefault().post(pingLunBean);
                        } else if ("0".equals(wantLearnBean.getRe())) {
                            ToastUtil.showToast(wantLearnBean.getInfo());
                        } else if ("-1".equals(wantLearnBean.getRe())){
                            ToastUtil.showToast(wantLearnBean.getInfo());
                            context.startActivity(new Intent(context, LoginForPersonalActivity.class));
                        }
                    }
                    break;
            }
        }
    };

    public CourseCommentRecyclerAdapter(Context context, List<CourseDetailCommentBean.DataBean.ListBean> listBeans, String lid) {
        this.context = context;
        this.listBeans = listBeans;
        this.lid = lid;
        ACacheUtlis cacheUtlis = ACacheUtlis.getInstance();
        if (cacheUtlis != null) {
            UserBean reqeustUser = cacheUtlis.getReqeustUser(context);
            if (reqeustUser != null) {
                token = reqeustUser.getToken();
            }
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = View.inflate(context, R.layout.comment_content_item_layout, null);
        com.runen.wnhz.runen.ui.adapter.puadapter.CourseCommentRecyclerAdapter.ViewHolder viewHolder  = new com.runen.wnhz.runen.ui.adapter.puadapter.CourseCommentRecyclerAdapter.ViewHolder(itemView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        final CourseDetailCommentBean.DataBean.ListBean listBean = listBeans.get(position);
        Glide.with(context).load(listBean.getHead_img()).into(holder.comment_userHeadImg);
        holder.text_commentUserName.setText(listBean.getUsername());
        holder.rtText_commentContent.setText(listBean.getContent());
        holder.text_commentTime.setText(listBean.getAddtime());
        holder.text_giveTheThumbsUpNum.setText(listBean.getRecommed());
        holder.list_huiFu.setLayoutManager(new LinearLayoutManager(context,LinearLayoutManager.VERTICAL,false));
       CourseCommentRecordRecyclerAdapter adapter = new CourseCommentRecordRecyclerAdapter(context, listBean.getSlist(),lid);
        holder.list_huiFu.setAdapter(adapter);
        String isRecommed = listBean.getIs_recommed();
        if ("1".equals(isRecommed)) {
            hasGivenThumbsUp = true;
            Glide.with(context).load(R.mipmap.have_want_learn_xin).into(holder.image_giveTheThumbsUp);
        } else {
            hasGivenThumbsUp = false;
            Glide.with(context).load(R.mipmap.icon_want).into(holder.image_giveTheThumbsUp);
        }
        holder.image_giveTheThumbsUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String id = listBean.getId();
                if (hasGivenThumbsUp) {
                    cancleWantCollection(holder,id);
                } else {
                    giveTheThumbsUp(holder,id);
                }
            }
        });
        holder.text_reply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                messageFragment.commentDialog.show();
            }
        });
    }

    @Override
    public int getItemCount() {
        if (listBeans != null) {
            return listBeans.size();
        } else {
            return 0;
        }
    }

    private void giveTheThumbsUp(final ViewHolder holder,String id) {
        if (token != null && id != null) {
            FormBody formBody = new FormBody.Builder().add("token", token).add("type", "3").add("id", id).build();
            Request request = new Request.Builder().url(NetUtils.USER_LESSON_COLLECTION).post(formBody).build();
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(request);
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    handler.sendEmptyMessage(0);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        handleWantLearnData(response,holder);
                    } catch (IOException e) {
                        e.printStackTrace();
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        }
    }

    private void handleWantLearnData(Response response,ViewHolder holder) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String json = responseBody.string();
                wantLearnBean = new Gson().fromJson(json, WantLearnBean.class);
                Message message = Message.obtain();
                message.what = 1;
                message.obj = holder;
                handler.sendMessage(message);
            }
        }

    }

    private void cancleWantCollection(final ViewHolder holder,String id) {
        if (token != null && id != null) {
            FormBody formBody = new FormBody.Builder().add("token", token).add("type", "3").add("id", id).add("del", "1").build();
            //构建一个网络请求，从指定网址上面请求数据
            Request.Builder requestBuilder = new Request.Builder()
                    .url(NetUtils.USER_LESSON_COLLECTION)
                    .post(formBody);
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(requestBuilder.build());
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    handler.sendEmptyMessage(0);
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    try {
                        handleCancleWantLearnData(response,holder);
                    } catch (IOException e) {
                        e.printStackTrace();
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        }
    }

    private void handleCancleWantLearnData(Response response,ViewHolder holder) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String json = responseBody.string();
                System.out.println("json -- = " + json);
                wantLearnBean = new Gson().fromJson(json, WantLearnBean.class);
                Message message = Message.obtain();
                message.what = 2;
                message.obj = holder;
                handler.sendMessage(message);
            }
        }

    }

    class ViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.comment_userHeadImg)
        CircleImageView comment_userHeadImg;
        @BindView(R.id.text_commentUserName)
        TextView text_commentUserName;
        @BindView(R.id.rtText_commentContent)
        TextView rtText_commentContent;
        @BindView(R.id.text_commentTime)
        TextView text_commentTime;
        @BindView(R.id.text_reply)
        TextView text_reply;
        @BindView(R.id.image_reply)
        ImageView image_reply;
        @BindView(R.id.text_giveTheThumbsUpNum)
        TextView text_giveTheThumbsUpNum;
        @BindView(R.id.image_giveTheThumbsUp)
        ImageView image_giveTheThumbsUp;
        @BindView(R.id.list_huiFu)
        RecyclerView list_huiFu;


        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}
